<?php
/**
 *
 * @author spring
 * @version 2014-6-7 上午9:37:58
 */
class  Controller_Bymaterial extends Controller_Admin {
    /**
     *汇率的新增查询与修改
     *
     */
    public function before()
    {
        try {
            ACL::Required('Bymaterial');
        } catch ( HTTP_Exception_403 $e ) {
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect ( URL::base (true) );
        }
        parent::before();
    }
    /**
     *
     * Description
     * 添加汇率界面
     */
    public function action_index()
    {
        $this->title='借料/备货登记查询';
        $content=View::factory("inventory/bymaterial");
        $this->response->body($content);
    }

    public function action_select()
    {
        $this->title='借料/备货登记查询';
        $content=View::factory("inventory/bymaterial");
        $date_type = isset($_GET['date_type'])?$_GET['date_type']:'bymaterial_date';//日期类型
        $date_from = isset($_GET['date_from'])?$_GET['date_from']:'';
        $date_to = isset($_GET['date_to'])?$_GET['date_to']:'';//日期
        $use_type = isset($_GET['use_type'])?$_GET['use_type']:2;//单据状态
        $sku = isset($_GET['sku'])?trim($_GET['sku']):'';
        $username = isset($_GET['username'])?trim($_GET['username']):'';//借料人

        $notice = '';
        if($sku!=''){
            $sku_id = inventory::select_productid($sku);
            if($sku_id==0){

                $notice='sorry，此sku不存在';
            }
        }

        if($notice==''){


        $sql = "SELECT count(0) as num FROM `bymaterials` WHERE 1 ";
        $sql_to = '';
        if($date_from!=''){
            $sql_to .=" AND ".$date_type.">'".$date_from." 00:00:00'";
        }
        if($date_to!=''){
            $sql_to .=" AND ".$date_type."<='".$date_to." 59:59:59'";
        }
        if($use_type!=2){
            $sql_to .=" AND status=".$use_type;
        }

        if($sku!=''){
            $sql_to .=" AND sku='".$sku."'";
        }
        if($username!=''){
            $sql_to .=" AND bymaterial_username LIKE '%".$username."%'";
        }

        if($sql_to!='')$sql .=$sql_to;
        $ordernum = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
        $per_page = 20;
        $pagination = Pagination::factory(array(
            'items_per_page' => $per_page,
            'total_items'    => $ordernum[0]['num'],
            'uri'	         => $this->request->uri(),
        ));

        $sql2 = "SELECT `id`, `bymaterial_username`, `bymaterial_renmark`, `bymaterial_date`, `sku`,
                `sku_name`, `num`, `plan_return_date`, `real_return_date`, `real_return_remark`, `add_time`,
                `update_time`, `register_userid`, `update_userid`, `status` FROM `bymaterials` WHERE 1 ";

        if($sql_to!='')$sql2 .=$sql_to;
        $current_page     = isset($_GET['page'])?$_GET['page']:1;
        $sql2     .=" order by id DESC LIMIT ".(($current_page-1)*$per_page).",".$per_page;
        $orders = DB::query(Database::SELECT,$sql2)->execute('newerp')->as_array();
        foreach($orders as $key=>$order){

            $orders[$key]['real_num'] = inventory::select_adapterstock($order['sku']);
            $user_id_name= ORM::factory('user')->where('id','=',$order['register_userid'])->find();
            $orders[$key]['register_username'] = $user_id_name->name;
            $orders[$key]['bymaterial_date'] = date('Y年m月d日',strtotime($orders[$key]['bymaterial_date']));
            $orders[$key]['plan_return_date'] = date('Y年m月d日',strtotime($orders[$key]['plan_return_date']));
        }
        //针对没有借料的sku查库存
        if($sku!='' && empty($orders)){
            $orders[0]['sku'] = $sku;
            $orders[0]['real_num'] = inventory::select_adapterstock($sku);
            $cnname  = Skusystemapi::getSkuCnname($sku);
            $orders[0]['sku_name'] = isset($cnname[0]['name'])?$cnname[0]['name']:'';

        }
        }else{
                Message::error($notice);
        }
        $content->set("values",$orders);
        $content->set("pagination",$pagination);
        $content->set("date_type",$date_type);
        $content->set("date_from",$date_from);
        $content->set("date_to",$date_to);
        $content->set("use_type",$use_type);
        $content->set("sku",$sku);
        $content->set("num", $ordernum[0]['num']);
        $content->set("username",$username);
        $this->response->body($content);
    }
    public function action_add()
    {
        $this->title='借料/备货登记';
        $content=View::factory("inventory/bymaterial_add");
        //加载仓库配置信息--begin --
        $warehouseid = Kohana::$config->load('warehouse')->warehouse_id;
        //---end--
        $error_arr = array();//错误数组信息

        //判断是否有文件提交
        if(isset($_FILES['xls']['tmp_name'])){
            set_time_limit(0);
            ini_set('memory_limit','500M');
            require_once(Kohana::find_file('vendor','PHPExcel/PHPExcel/IOFactory'));
            $xls         = $_FILES['xls']['tmp_name'];
            $objPHPExcel = PHPExcel_IOFactory::load($xls);
            $data        = $objPHPExcel->getActiveSheet()
                ->toArray(NULL,TRUE,TRUE,TRUE);
            $num         = count($data);

            for($i=2;$i<=$num;$i++){
				if(empty($data[$i]['A']) && empty($data[$i]['B']) && empty($data[$i]['D']))break;
                $data[$i]['A'] = trim($data[$i]['A']);
                $data[$i]['B'] = trim($data[$i]['B']);
                $data[$i]['C'] = trim($data[$i]['C']);
                $data[$i]['D'] = trim($data[$i]['D']);
                $data[$i]['F'] = trim($data[$i]['F']);
                if(empty($data[$i]['A']) ||empty($data[$i]['B']) ||empty($data[$i]['C']) ||empty($data[$i]['D']) ||empty($data[$i]['F'])){
                    $error_arr[] = '第'.$i.'行有数据为空，请检查借料人/借料原因/借料日期/sku/预计归还日期';

                }

                if(!$this->isdate($data[$i]['C'])){
                    $error_arr[] = '第'.$i.'行借料日期格式不对';
                }
                if(!$this->isdate($data[$i]['F'])){
                    $error_arr[] = '第'.$i.'行预计还料日期格式不对';
                }

                if(inventory::select_productid($data[$i]['D'])==0){
                    $error_arr[] = '第'.$i.'sku不存在';
                }
                if(intval($data[$i]['E'])==0){
                    $error_arr[] = '第'.$i.'借料数量不能为0';
                }
            }
            //检查没问题后上传
            if(empty($error_arr)){
				$real_num=0;
                for($i=2;$i<=$num;$i++){
					if(empty($data[$i]['A']) && empty($data[$i]['B']) && empty($data[$i]['D']))break;
                    $bym = ORM::factory('bymaterial');
                    $bym->bymaterial_username = $data[$i]['A'];
                    $bym->bymaterial_renmark = $data[$i]['B'];
                    $bym->bymaterial_date = $data[$i]['C'];
                    $bym->sku = $data[$i]['D'];
                    $cnname  = Skusystemapi::getSkuCnname($data[$i]['D']);
                    $bym->sku_name = isset($cnname[0]['name'])?$cnname[0]['name']:'';
                    $bym->num = $data[$i]['E'];
                    $bym->plan_return_date = $data[$i]['F'];
                    $bym->add_time = date('Y-m-d H:i:s',time());;
                    $bym->register_userid = User::active_user()->id;
                    $bym->status = 0;
                    $bym->warehouseid = $warehouseid;
                    $bym->save();
                    /*
                    if($bym->saved()){
                        $insert_id = (string)$bym->pk();
                        $id = $insert_id.sprintf('%03d',$warehouseid);
                        DB::update('bymaterials')->set(array('id'=>$id))->where('aid','=',$insert_id)->execute('newerp');
                    }
                    */
                    if($bym->saved())
                    $real_num++;
                }
                $error_arr['num'] = '恭喜上传成功'.$real_num.'条记录';
            }

        }

        $content->set("error_arr",$error_arr);
        $this->response->body($content);
    }

    /**
     * 下载模板
     */
    public function action_down_template()
    {
        $this->title = '下载模版';
        require_once(Kohana::find_file('vendor','PHPExcel/PHPExcel/IOFactory'));
        $this->objReader = PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel     = new PHPExcel();
        $objPHPExcel->getProperties()
            ->setCreator("newerp")
            ->setLastModifiedBy("newerp")
            ->setTitle("Office 2003 XLSX Test Document")
            ->setSubject("Office 2003 XLSX Test Document")
            ->setDescription("Test document for Office 2003 XLSX, generated using PHP classes.")
            ->setKeywords("office 2003 openxml php")
            ->setCategory("Test result file");
        $objActSheet = $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet->setCellValue('A1','借料人');
        $objActSheet->setCellValue('B1','借料原因');
        $objActSheet->setCellValue('C1','借料日期');
        $objActSheet->setCellValue('D1','sku');
        $objActSheet->setCellValue('E1','借出数量');
        $objActSheet->setCellValue('F1','预计归还日期');
        $objActSheet->setCellValue('A2','test');
        $objActSheet->setCellValue('B2','借出拍照');
        $objActSheet->setCellValue('C2','2015-04-25');
        $objActSheet->setCellValue('D2','AAA001');
        $objActSheet->setCellValue('E2','0');
        $objActSheet->setCellValue('F2','2015-04-26');

        $objPHPExcel->getActiveSheet()
            ->setTitle('load');
        $objPHPExcel->setActiveSheetIndex(0);
        $day = date("m-d");
        ob_end_clean();
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header('Content-Disposition: attachment;filename="'.$day.'借料备货登记.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $objWriter->save('php://output');
        exit;
    }


    /**
     * 确认归还
     */
    public function action_updatereturn()
    {
        $byid = $_GET['byid'];
        $return_remark = $_GET['return_remark'];
        $bym = ORM::factory('bymaterial',$byid);
        $bym->real_return_remark = $return_remark;
        $bym->real_return_date = date('Y-m-d');
        $bym->update_time= date('Y-m-d H:i:s');
        $bym->update_userid = User::active_user()->id;
        $bym->status = 1;
        $bym->save();
        if($bym->saved()){
            echo 'ok';
        }else{
            echo '确认归还操作失败';
        }

    }

    /**判断日期格式是否正确
     * @param $str
     * @param string $format
     * @return bool
     *
     *
     */
    public function isdate($str,$format="Y-m-d"){

        $unixTime=strtotime($str);
        $checkDate= date($format,$unixTime);
        $checkDate2= date("Y-n-j",$unixTime);

        if($checkDate==$str || $checkDate2==$str)
            return true;
        else
            return false;
    }
}
